﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using Devv.Core.Erroo;
using Devv.Core.Utils;
using Devv.FreshTracker.Properties;

namespace Devv.FreshTracker
{
	public partial class OptionsForm : Form
	{
		#region Properties

		public Boolean APIDetailsUpdated { get; set; }

		#endregion

		#region Loading

		public OptionsForm()
		{
			InitializeComponent();

			APIDetailsUpdated = false;

			Icon = Resources.App;
		}

		private void OptionsForm_Load(object sender, EventArgs e)
		{
			Text += " (" + AssemblyUtil.GetFriendlyVersion(Assembly.GetEntryAssembly()) + ")";

			// API and registration

			txtApiUrl.Text = Options.ApiUrl;
			txtApiToken.Text = Options.ApiToken;

			// Appearance

			for (Int32 i = 10; i > 3; i--)
			{
				cboOpacity.Items.Add(i * 10 + "%");
			}

			cboOpacity.SelectedIndex = cboOpacity.FindString(Options.Opacity * 100 + "%");
			chkMini.Checked = Options.ShowMini;
			chkTopMost.Checked = Options.TopMost;
			chkStartMinimized.Checked = Options.StartMinimized;

			// Time tracking

			chkRulesEnabled.Checked = Options.EnableRules;
			chkShowNotes.Checked = Options.ShowNotes;

			cboRound.DataSource = Options.TimerRoundCollection;
			cboAutoStop.DataSource = Options.TimerAutoStopCollection;
			cboRound.SelectedItem = DoubleItem.FindInList(Options.TimerRoundCollection, Options.Round);
			cboAutoStop.SelectedItem = DoubleItem.FindInList(Options.TimerAutoStopCollection, Options.AutoStop);

			// Other settings

			chkCheckUpdates.Checked = Options.CheckUpdates;
			chkDebug.Checked = Options.Debug;
			chkReportErrors.Checked = Options.ReportErrors;

			if (!String.IsNullOrEmpty(App.LicensedTo))
			{
				lblLicenseEmail.Text = App.LicensedTo;
			}
			
			// Start the form!

			imgRegistration_Click(null, null);
		}

		private void OptionsForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			e.Cancel = false; 
			
			if (Program.Closing)
			{
				return;
			}

			Options.Save();

			if (APIDetailsUpdated)
			{
				if (Options.FirstRun && MessageBox.Show(Messages.FirstExecutionOpenRules, Messages.AutoTracking, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
				{
					Program.ShowRulesForm();
				}
			}

			Dispose();
		}

		private void OptionsForm_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
		{
			HideImageHelp();
		}

		#endregion

		#region Tabs

		private void imgRegistration_Click(object sender, EventArgs e)
		{
			HideImageHelp();

			imgRegistration.BackgroundImage = Resources.OptionBg;
			imgAppearance.BackgroundImage = null;
			imgTimeTracking.BackgroundImage = null;
			imgOther.BackgroundImage = null;

			lblRegistration.ForeColor = SystemColors.ControlText;
			lblAppearance.ForeColor = SystemColors.GrayText;
			lblTimeTracking.ForeColor = SystemColors.GrayText;
			lblOther.ForeColor = SystemColors.GrayText;

			boxRegistration.BringToFront();
		}

		private void imgAppearance_Click(object sender, EventArgs e)
		{
			HideImageHelp();

			imgRegistration.BackgroundImage = null;
			imgAppearance.BackgroundImage = Resources.OptionBg;
			imgTimeTracking.BackgroundImage = null;
			imgOther.BackgroundImage = null;

			lblRegistration.ForeColor = SystemColors.GrayText;
			lblAppearance.ForeColor = SystemColors.ControlText;
			lblTimeTracking.ForeColor = SystemColors.GrayText;
			lblOther.ForeColor = SystemColors.GrayText;

			boxAppearance.BringToFront();
		}

		private void imgTimeTracking_Click(object sender, EventArgs e)
		{
			HideImageHelp();

			imgRegistration.BackgroundImage = null;
			imgAppearance.BackgroundImage = null;
			imgTimeTracking.BackgroundImage = Resources.OptionBg;
			imgOther.BackgroundImage = null;

			lblRegistration.ForeColor = SystemColors.GrayText;
			lblAppearance.ForeColor = SystemColors.GrayText;
			lblTimeTracking.ForeColor = SystemColors.ControlText;
			lblOther.ForeColor = SystemColors.GrayText;

			boxTracking.BringToFront();
		}

		private void imgOther_Click(object sender, EventArgs e)
		{
			HideImageHelp();

			imgRegistration.BackgroundImage = null;
			imgAppearance.BackgroundImage = null;
			imgTimeTracking.BackgroundImage = null;
			imgOther.BackgroundImage = Resources.OptionBg;

			lblRegistration.ForeColor = SystemColors.GrayText;
			lblAppearance.ForeColor = SystemColors.GrayText;
			lblTimeTracking.ForeColor = SystemColors.GrayText;
			lblOther.ForeColor = SystemColors.ControlText;

			boxOther.BringToFront();
		}

		#endregion

		#region Registration (license)

		private void linkFreshBooks_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			Process.Start(FreshBooks.REFER_URL);
		}

		#endregion

		#region API details

		private void txtApi_TextChanged(object sender, EventArgs e)
		{
			imgLoadingApi.Visible = false;

			txtApiUrl.ForeColor = SystemColors.WindowText;
			txtApiToken.ForeColor = SystemColors.WindowText;
		}

		private void linkApiWhere_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			ShowHelpImage(Resources.TutorialAPI);
		}

		private void butLogin_Click(object sender, EventArgs e)
		{
			if (!RegexUtil.Test(txtApiUrl.Text, RegexUtil.Url))
			{
				MessageBox.Show(Messages.WarningInvalidApiUrl, Messages.API, MessageBoxButtons.OK, MessageBoxIcon.Warning);
				txtApiUrl.Focus();
				return;
			}

			if (txtApiToken.Text.Length < 5)
			{
				MessageBox.Show(Messages.WarningInvalidApiToken, Messages.API, MessageBoxButtons.OK, MessageBoxIcon.Warning);
				txtApiToken.Focus();
				return;
			}

			Options.ApiUrl = txtApiUrl.Text.Trim();
			Options.ApiToken = txtApiToken.Text.Trim();

			if (!Options.ApiUrl.Contains("http") && !Options.ApiUrl.Contains("."))
			{
				String url = FreshBooks.DEFAULT_API_URL.Replace("#COMPANY", Options.ApiUrl);
				String msg = Messages.ConfirmApiUrl.Replace("#", url);

				if (MessageBox.Show(msg, Messages.API, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
				{
					Options.ApiUrl = url;
					txtApiUrl.Text = url;
				}
			}

			txtApiUrl.Enabled = false;
			txtApiToken.Enabled = false;
			butLogin.Enabled = false;

			imgLoadingApi.Image = Resources.IcoLoading16;
			imgLoadingApi.Visible = true;

			workerLogin.RunWorkerAsync();
		}

		private void workerLogin_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
		{
			e.Result = 0;

			try
			{
				e.Result = FreshBooks.TestLogin(txtApiUrl.Text, txtApiToken.Text);
			}
			catch (Exception ex)
			{
				ErrorHandler.Handle(ex);
			}
		}

		private void workerLogin_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
		{
			Int64 id = Convert.ToInt64(e.Result);

			if (id > 0)
			{
				Options.UserId = id;
				Options.Save();

				txtApiUrl.ForeColor = Color.DarkGreen;
				txtApiToken.ForeColor = Color.DarkGreen;
				imgLoadingApi.Image = Resources.IcoOk16;

				APIDetailsUpdated = true;
			}
			else
			{
				MessageBox.Show(Messages.ErrorInvalidLogin, Messages.API, MessageBoxButtons.OK, MessageBoxIcon.Warning);

				Options.UserId = 0;

				txtApiUrl.ForeColor = Color.Red;
				txtApiToken.ForeColor = Color.Red;
				imgLoadingApi.Image = Resources.IcoError16;
			}

			txtApiUrl.Enabled = true;
			txtApiToken.Enabled = true;
			butLogin.Enabled = true;
		}

		#endregion

		#region Appearance

		private void cboOpacity_SelectedIndexChanged(object sender, EventArgs e)
		{
			Options.Opacity = Convert.ToDouble(cboOpacity.SelectedItem.ToString().Replace("%", String.Empty)) * 0.01;
			Program.MainFormObj.Opacity = Options.Opacity;
		}

		private void chkMini_CheckedChanged(object sender, EventArgs e)
		{
			Options.ShowMini = chkMini.Checked;
			Program.MainFormObj.CloseMini();
		}

		private void chkTopMost_CheckedChanged(object sender, EventArgs e)
		{
			Options.TopMost = chkTopMost.Checked;

			Program.MainFormObj.TopMost = Options.TopMost;
		}

		private void chkStartMinimized_CheckedChanged(object sender, EventArgs e)
		{
			Options.StartMinimized = chkStartMinimized.Checked;
		}

		#endregion

		#region Session tracking options

		private void cboRound_SelectedIndexChanged(object sender, EventArgs e)
		{
			Options.Round = ((DoubleItem)cboRound.SelectedItem).Value;
		}

		private void cboAutoStop_SelectedIndexChanged(object sender, EventArgs e)
		{
			Options.AutoStop = ((DoubleItem)cboAutoStop.SelectedItem).Value;
		}

		private void chkRulesEnabled_CheckedChanged(object sender, EventArgs e)
		{
			Options.EnableRules = chkRulesEnabled.Checked;

			Program.MainFormObj.SetAutoTracking();
		}

		private void chkShowNotes_CheckedChanged(object sender, EventArgs e)
		{
			Options.ShowNotes = chkShowNotes.Checked;
		}

		private void linkOpenRules_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
		{
			Program.ShowRulesForm();
		}

		#endregion

		#region Other options

		private void chkCheckUpdates_CheckedChanged(object sender, EventArgs e)
		{
			Options.CheckUpdates = chkCheckUpdates.Checked;
		}

		private void chkDebug_CheckedChanged(object sender, EventArgs e)
		{
			Options.Debug = chkDebug.Checked;
			Config.DoShowDialog = Options.Debug;
		}

		private void chkReportErrors_CheckedChanged(object sender, EventArgs e)
		{
			Options.ReportErrors = chkReportErrors.Checked;
		}

		private void imgOpenErrors_Click(object sender, EventArgs e)
		{
			if (Directory.Exists(Config.LogPath))
			{
				Process.Start(Config.LogPath);
			}
			else
			{
				MessageBox.Show(Messages.NoErrorsLogged);
			}
		}

		private void linkDonate_Click(object sender, EventArgs e)
		{
			Process.Start(App.DONATE_URL);
		}

		#endregion

		#region Help images

		private void imgHelp_Click(object sender, EventArgs e)
		{
			HideImageHelp();
		}

		private void ShowHelpImage(Bitmap img)
		{
			imgHelp.Image = img;

			imgHelp.BringToFront();
			imgHelp.Visible = true;
		}

		private void HideImageHelp()
		{
			if (imgHelp.Visible)
			{
				imgHelp.Visible = false;
			}
		}

		#endregion
	}
}